﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ditto.Models;

namespace Ditto.Controllers
{ 
    public class UsersController : Controller
    {
        private DittoEntities db = new DittoEntities(); //to deprecate
        UserRepository userRepository;

        public UsersController()
            : this(new UserRepository())
        {

        }

        public UsersController(UserRepository repository)
        {
            this.userRepository = repository;
        }

        //
        // GET: /Users/

        public ViewResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /Users/Details/5
        public ViewResult Details(string id)
        {
            User user = db.Users.Single(u => u.UserID == id);
            return View(user);
        }

        [Authorize]
        public ActionResult FriendStatus(string otherUser)
        {
            if (otherUser == User.Identity.Name)
                return View();

            this.userRepository = new UserRepository();
            UserRelationship rel1 = userRepository.FindRelationship(User.Identity.Name, otherUser);
            UserRelationship rel2 = userRepository.FindRelationship(otherUser, User.Identity.Name);

            FriendStatus status = new FriendStatus(otherUser);

            if (rel1 == null && rel2 == null)
                status.Type = Models.FriendStatus.StatusType.None;
            else if (rel1 == null && rel2 != null)
            {
                if (rel2.IsConfirmed)
                    status.Type = Models.FriendStatus.StatusType.Confirmed;
                else
                    status.Type = Models.FriendStatus.StatusType.Requested;
            }
            else if (rel1 != null && rel2 == null)
            {
                if (rel1.IsConfirmed)
                    status.Type = Models.FriendStatus.StatusType.Confirmed;
                else
                    status.Type = Models.FriendStatus.StatusType.Requesting;
            }
            else
                throw new Exception("This case should not occur");

            return View(status);
        }

        [Authorize]
        public ActionResult RequestFriendship(string requestedUser, string message)
        {
            if (String.IsNullOrEmpty(requestedUser))
                throw new ArgumentNullException();

            if (requestedUser == User.Identity.Name)
                return View();

            if (String.IsNullOrEmpty(message))
                message = "";


            UserRelationship rel = this.userRepository.FindRelationship(User.Identity.Name, requestedUser);
            if (rel == null)
            {
                rel = UserRelationship.CreateUserRelationship(User.Identity.Name, requestedUser, false, message);

                try
                {
                    this.userRepository.AddRelationship(rel);
                    this.userRepository.Save();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            FriendStatus status = new FriendStatus(requestedUser);
            status.Type = Models.FriendStatus.StatusType.Requesting;

            return PartialView("FriendStatus", status);
        }

        [Authorize]
        public ActionResult ConfirmFriendship(string confirmedUser)
        {
            UserRelationship rel = this.userRepository.FindRelationship(confirmedUser, User.Identity.Name);

            if (rel != null)
            {
                rel.IsConfirmed = true;

                try
                {
                    this.userRepository.Save();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            FriendStatus status = new FriendStatus(confirmedUser);
            status.Type = Models.FriendStatus.StatusType.Confirmed;

            return PartialView("FriendStatus", status);
        }

        [Authorize]
        public ActionResult RemoveFriendship(string removedUser)
        {
            UserRelationship rel1 = this.userRepository.FindRelationship(User.Identity.Name, removedUser);
            UserRelationship rel2 = this.userRepository.FindRelationship(removedUser, User.Identity.Name);

            try
            {
                if (rel1 != null)
                    this.userRepository.DeleteRelationship(rel1);

                if (rel2 != null)
                    this.userRepository.DeleteRelationship(rel2);

                this.userRepository.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            FriendStatus status = new FriendStatus(removedUser);
            status.Type = Models.FriendStatus.StatusType.None;

            return PartialView("FriendStatus", status);
        }

        public ViewResult Reputation(string id)
        {
            Reputation reputation = userRepository.GetUserReputation(id);


            return View(reputation);
        }

        public ViewResult Friends(string id)
        {
            var friends = this.userRepository.FindConfirmedFriends(id);
            return View(new Friends(friends.ToList()));
        }

        public ViewResult FriendRequests(string id)
        {
            var requests = this.userRepository.FindRequestingFriends(id);
            return View(new UserRequests(requests));
        }

        public ActionResult ItemsPosted(string id)
        {
            ItemRepository itemRepository = new ItemRepository();
            var items = itemRepository.FindByUser(id);

            return View(new Items(items));
        }

        public ViewResult UserSummary(User user)
        {
            return View(user);
        }

        //Transaction history
        public ViewResult History(string id)
        {
            return View(id);
        }

        public ActionResult Photo(string id)
        {
            throw new NotImplementedException();
            //this.userRepository = new UserRepository();
            //User user = userRepository.GetUser(id);
            //return View(user);
        }

        [HttpPost]
        public ActionResult AddPhoto(string id, HttpPostedFileBase file)
        {
            this.userRepository = new UserRepository();
            ImageRepository imageRepository = new ImageRepository();

            User user = userRepository.GetUser(id);

            if (user.UserID != User.Identity.Name)
                return View("InvalidOwner");

            try
            {
                Image image = new Image(file);
                imageRepository.AddUserImage(image, user);

                UpdateModel(user, "User");

                userRepository.Save();

                return RedirectToAction("Details", new { id = user.UserID });
            }
            catch
            {
                return RedirectToAction("Details", new { id = user.UserID });
            }
        }

        public ActionResult DeletePhoto(string id)
        {
            this.userRepository = new UserRepository();
            ImageRepository imageRepository = new ImageRepository();

            User user = userRepository.GetUser(id);

            if (user.UserID != User.Identity.Name)
                return View("InvalidOwner");

            try
            {
                imageRepository.DeleteUserImage(user);

                UpdateModel(user, "User");

                userRepository.Save();

                return RedirectToAction("Details", new { id = user.UserID });
            }
            catch
            {
                return View(user);
            }
        }

        //
        // GET: /Users/Create
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Users/Create

        [HttpPost]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.AddObject(user);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(user);
        }
        
        //
        // GET: /Users/Edit/5
 
        public ActionResult Edit(string id)
        {
            User user = db.Users.Single(u => u.UserID == id);
            return View(user);
        }

        //
        // POST: /Users/Edit/5

        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Attach(user);
                db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        //
        // GET: /Users/Delete/5
 
        public ActionResult Delete(string id)
        {
            User user = db.Users.Single(u => u.UserID == id);
            return View(user);
        }

        //
        // POST: /Users/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {            
            User user = db.Users.Single(u => u.UserID == id);
            db.Users.DeleteObject(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}